<?php
/**
 * ***********************************************************************************
 * 咨询鲤-知识商城PC端店铺
 * 
 * 验证登录中间件
 * 
 * @author Mr.RJH
 * @date 2025-09-03
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\middleware;

use think\Request;
use think\exception\HttpResponseException;

/**
 * @deprecated
 * 检测用户登录
 * Class CheckLogin
 * @package app\middleware
 */
class CheckLogin
{

    public function handle(Request $request, \Closure $next)
    {
        
        $userId = session('user.id');
        
        // 需要登录验证的路由规则
        $auth_rule = [
            '/user/',

            '#course/study#',
            '#course/study_verify_auth#',
            
            '#exam/practice_detail#',
            '#exam/practice#',

            '#question/practice_set#',
            '#question/reset_chapter_process#',
            '#question/chapter_practice#',
            '#question/get_question_info#',
            '#question/favorites_add#',
            '#question/practice_report#',

            '#order/get_free_power#',
            '#order/prepare#',
            '#order/create#',
            '#order/continue_pay#',
            '#order/check_order_pay#',
        ];
        
        $currentPath = $request->baseUrl();
        // 检查是否需要登录
        if ($this->requiresAuth($currentPath, $auth_rule) && empty($userId)) {
            // AJAX请求返回JSON
            if ($request->isAjax()) {
                return json(['code' => 1,'msg' => '你还未登录，请先登录']);
            }
            return redirect('/');
        }
        return $next($request);
    }

    /**
     * 路由验证
     * 
     * @return bool
     */
    protected function requiresAuth($path, $patterns)
    {
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $path)) { 
                return true;
            }
        }
        return false;
    }
}